import React, { useState, useEffect } from 'react';
import { Button, Form, Input, InputNumber, Select, message} from 'antd';
// import { Image, Upload } from 'antd';
import ADD_EDIT_CUSTOM_MODAL from '@Components/CustomModal/Add_Eidt_Custom_Modal';
// import { PlusOutlined } from '@ant-design/icons'; // 上传图片的加号icon

// 创建组件,使用hooks
const IndexAddEidtForm = ({IndexAddEidtTypeObject, Visible, Modal_Cancel, PushData_Object}) => {
  
  const [ModalTitle, setModalTitle] = useState(''); // 新增/编辑弹窗标题
  const [EidtRowDataID, setEidtRowDataID] = useState(''); // 编辑数据id
  const {TextArea } = Input;
  /**
   * @date: 2024-10-07 00:09:42
   * @description: 图片上传个数处理
   * tip: 等有了上传接口将其整块还原
   * @param {Function | getBase64} 拿到图片Base64
   * @param {Object | fileList}  图片列表
   * @param {Boolean | previewOpen}  图片预览弹窗状态
   * @param {String | previewImage}  图片预览地址
   * @modifyContent:
   * @author: Forever丿顾北
  **/
  // const action = '' // 上传图片服务地址
  // const FileListNum = 3 // 上传图片最多上传图片个数
  // const getBase64 = (file) => new Promise((resolve, reject) => {
  //   const reader = new FileReader();
  //   reader.readAsDataURL(file);
  //   reader.onload = () => resolve(reader.result);
  //   reader.onerror = (error) => reject(error);
  // });
  // const [previewOpen, setPreviewOpen] = useState(false);
  // const [previewImage, setPreviewImage] = useState('');
  // const [fileList, setFileList] = useState([])
  
  /**
   * @date: 2024-10-07 00:18:25
   * @description:点击文件链接或预览图标时的回调
   * * tip: 等有了上传接口将其整块还原
   * @author: Forever丿顾北
   * @param { Object | file} 上传文件
  **/
//  const onPreview = async (file) => {
//     if (!file.url && !file.preview) {
//       file.preview = await getBase64(file.originFileObj);
//     }
//     setPreviewImage(file.url || file.preview);
//     setPreviewOpen(true);
//   };
  /**
   * @date: 2024-10-07 00:20:01
   * @description:上传文件改变时的回调，上传每个阶段都会触发该事件
   * * tip: 等有了上传接口将其整块还原
   * @author: Forever丿顾北
   * @param{ type }: ${参数}
   * @param { type|* } ${参数名}: ${参数}
   * @returns{ type|* }: ${返回参数}
  **/
  // const onChange = ({ fileList }) => {
  //   console.log('onChange fileList', fileList)
  //   setFileList(fileList)
  // };
  /**
   * @date: 2024-09-10 20:43:54
   * @description: 创建表单实例
   * @modifyContent:
   * @author: Forever丿顾北
  **/
  const [Add_Eidt_ModalForm] = Form.useForm();  
  /**
   * @date: 2024-09-10 20:13:43
   * @description: 新增/编辑弹窗取消
   * @modifyContent:
   * @author: Forever丿顾北
  **/
  const Add_Eidt_Custom_Modal_Cancel = () => {
    Add_Eidt_ModalForm.resetFields(); // 重置表单
    Modal_Cancel(false)
  };
  /**
   * @date: 2024-09-10 20:20:47
   * @description: 新增/编辑弹窗确定提交
   * @modifyContent:
   * @author: Forever丿顾北
  **/
  const Add_Eidt_Custom_Modal_Submit = () => {
    Add_Eidt_ModalForm.validateFields().then(val => {
      console.log('表单验证通过', val)
      let PushData = {
        productName:val.productName, // 商品名称
        productPrice: val.productPrice, // 商品价格
        productNum: val.productNum, // 商品库存
        productDesc: val.productDesc, // 商品描述
        productType: val.productType, // 商品类型
        ModalType: IndexAddEidtTypeObject.ModalType
      }
      if (IndexAddEidtTypeObject.ModalType !== 'add') {
        PushData.id = EidtRowDataID;
      }
      PushData_Object(PushData)
    }).catch(err => {
      console.log('表单验证失败', err)
      message.error(
        '请按要求填写', 
        [2]
      )
      return false;
    })
  };
  
  useEffect(() => {
    if (IndexAddEidtTypeObject.ModalType === 'add') {
      setModalTitle('新增商品');
    } else {
      setModalTitle('编辑商品');
      if(Object.keys(IndexAddEidtTypeObject.RowData).length === 0 && IndexAddEidtTypeObject.RowData.constructor === Object) {
        return;    
      } else {
        // 将当前行数据进行一次深拷贝
        const deepCopyData = JSON.parse(JSON.stringify(IndexAddEidtTypeObject.RowData));
        setEidtRowDataID(deepCopyData.id) // 编辑数据id
        // 表单数据回显
        Add_Eidt_ModalForm.setFieldsValue(deepCopyData);
      }
      
    }
  }, [IndexAddEidtTypeObject, Add_Eidt_ModalForm]);
  
  /**
   * @date: 2024-09-11 00:20:04
   * @description: 弹窗footer
   * @modifyContent:
   * @author: Forever丿顾北
  **/
  const footerContent = [
    <Button key="back" onClick={Add_Eidt_Custom_Modal_Cancel}>取消</Button>,
    <Button key="submit" type="primary" onClick={Add_Eidt_Custom_Modal_Submit}>提交</Button>,
  ];
  /**
   * @date: 2024-10-07 00:21:13
   * @description: 上传商品图片的上传按钮
   * * tip: 等有了上传接口将其整块还原
   * @modifyContent:
   * @author: Forever丿顾北
  **/
  // const uploadButton = (
  //   <button style={{border: 0,background: 'none',}} type="button">
  //     <PlusOutlined />
  //     <div style={{marginTop: 8,}}>
  //       上传
  //     </div>
  //   </button>
  // );
  return (
    <div>
      {/* 新增编辑弹窗 */}
      <ADD_EDIT_CUSTOM_MODAL
        visible={Visible}
        title={ModalTitle}
        footer={footerContent}
        onCancel={Add_Eidt_Custom_Modal_Cancel}
      >
        <Form
            form={Add_Eidt_ModalForm}
            labelCol={{span: 4}}
            wrapperCol={{span: 20}}
            labelAlign={'right'}
            onFinish={Add_Eidt_Custom_Modal_Submit}
          >
            <Form.Item
              label="商品名称"
              name='productName'
              rules={[
                {required: true, message: '请输入商品名称'}
              ]}
            >
              <Input placeholder="请输入商品名称..." allowClear/>
            </Form.Item>
            
            <Form.Item
              label="商品单价"
              name='productPrice'
              rules={[
                {required: true, message: '请输入商品单价'}
              ]}
            >
              <InputNumber  style={{width: '100%'}} step={1} precision={2} min={0} datatype={0}  placeholder="请输入商品单价..."/>
            </Form.Item>

            <Form.Item
              label="商品库存"
              name='productNum'
              rules={[
                {required: true, message: '请输入商品库存'}
              ]}
            >
              <InputNumber  style={{width: '100%'}} step={1} min={0} datatype={0}  placeholder="请输入商品库存..."/>
            </Form.Item>

            <Form.Item
              label="商品类型"
              name='productType'
              rules={[
                {required: true, message: '请选择商品类型'}
              ]}
            > 
              <Select 
                options={[
                  { value: '手机', label: '手机' },
                  { value: '相机', label: '相机' },
                  { value: '耳机', label: '耳机' },
                  { value: '电脑', label: '电脑' },
                  { value: '手表', label: '手表' },
                ]}
                placeholder="请选择商品类型..."
                notFoundContent="暂无数据"
                allowClear
              />
            </Form.Item>

            <Form.Item
              label="商品描述"
              name='productDesc'
              rules={[
                {required: true, message: '请输入商品描述'}
              ]}
            >
              <TextArea
                rows={6}
                placeholder="请输入商品描述..." 
                allowClear
              />
            </Form.Item>

            {/* 2024年10月7日00:28:09 因为还没有上传图片API 至此关闭图片上传验证*/}
            {/* <Form.Item
              label="商品图片"
              name='productImg'
              rules={[
                {required: true, message: '请上传商品图片'},
              ]}
            >
              <Upload
                action={action}
                listType="picture-card"
                fileList={fileList}
                onPreview={onPreview}
                onChange={onChange}
              >
                {fileList.length >= FileListNum ? null : uploadButton}
              </Upload>
              {previewImage && (
                <Image wrapperStyle={{display: 'none',}}
                  preview={{
                    visible: previewOpen,
                    onVisibleChange: (visible) => setPreviewOpen(visible),
                    afterOpenChange: (visible) => !visible && setPreviewImage(''),
                  }}
                  src={previewImage}
                />
              )}
            </Form.Item> */}
        </Form>
      </ADD_EDIT_CUSTOM_MODAL>
      {/* 新增编辑弹窗END */}
    </div>
  );
}

export default IndexAddEidtForm;